package com.cheng.student.utils;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionGetter
{
    private static SqlSessionFactory sqlSessionFactory = null;
    static
    {
        setSqlSessionFactory();
    }

    //获取SqlSession对象
    public static SqlSession getSqlSession()
    {

        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        return sqlSession;
    }

    //获取一个factory对象
    private static void setSqlSessionFactory()
    {
        InputStream resourceAsStream = null;
        try
        {
            //获取输入流
            resourceAsStream = Resources.getResourceAsStream("MybatisConfig.xml");
        }
        catch (IOException e)
        {
            System.out.println("配置文件加载失败");
        }
        //获得SqlSessionFactory对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        try
        {
            resourceAsStream.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println("stream关闭出现问题");
        }
    }

    //当配置文件更新时需要更新factory对象
    public void flush()
    {
        setSqlSessionFactory();
    }
}
